<template>
  <div class="page-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span class="title">费用类型管理</span>
          <div class="header-actions">
            <ImportButton 
              data-type="expense-types" 
              @import-success="handleImportSuccess"
            />
            <ExportButton
              :data="tableData"
              :columns="exportColumns"
              filename="费用类型"
            />
            <el-button type="primary" @click="handleAdd">
              <el-icon><Plus /></el-icon>
              新增费用类型
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :inline="true" class="search-form">
        <el-form-item label="类型名称">
          <el-input v-model="searchForm.name" placeholder="请输入类型名称" clearable />
        </el-form-item>
        <el-form-item label="费用类别">
          <el-select v-model="searchForm.category" placeholder="请选择类别" clearable>
            <el-option label="日常费用" value="daily" />
            <el-option label="差旅费用" value="travel" />
            <el-option label="办公费用" value="office" />
            <el-option label="人员费用" value="personnel" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 批量操作 -->
      <div v-if="selectedRows.length > 0" class="batch-actions">
        <el-alert :title="`已选择 ${selectedRows.length} 项`" type="info" :closable="false">
          <template #default>
            <div class="batch-buttons">
              <el-button size="small" type="success" @click="handleBatchEnable">批量启用</el-button>
              <el-button size="small" type="warning" @click="handleBatchDisable">批量停用</el-button>
              <el-button size="small" type="danger" @click="handleBatchDelete">批量删除</el-button>
            </div>
          </template>
        </el-alert>
      </div>

      <!-- 表格 -->
      <el-table :data="tableData" border stripe @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="编号" width="80" />
        <el-table-column prop="code" label="类型代码" width="120" />
        <el-table-column prop="name" label="类型名称" width="150" />
        <el-table-column prop="category" label="费用类别" width="120">
          <template #default="{ row }">
            <el-tag :type="getCategoryTag(row.category)">{{ getCategoryLabel(row.category) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="needApproval" label="需要审批" width="100">
          <template #default="{ row }">
            <el-tag :type="row.needApproval ? 'warning' : 'info'">
              {{ row.needApproval ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="limitAmount" label="限额" width="120">
          <template #default="{ row }">
            {{ row.limitAmount ? '¥' + row.limitAmount.toLocaleString() : '无限制' }}
          </template>
        </el-table-column>
        <el-table-column prop="accountSubject" label="会计科目" width="150" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="150" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
            <el-button 
              link 
              :type="row.status === 1 ? 'warning' : 'success'" 
              @click="handleToggleStatus(row)"
            >
              {{ row.status === 1 ? '停用' : '启用' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSearch"
        @current-change="handleSearch"
      />
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle"
      width="600px"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="类型代码" prop="code">
          <el-input v-model="form.code" placeholder="请输入类型代码" />
        </el-form-item>
        <el-form-item label="类型名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入类型名称" />
        </el-form-item>
        <el-form-item label="费用类别" prop="category">
          <el-select v-model="form.category" placeholder="请选择类别">
            <el-option label="日常费用" value="daily" />
            <el-option label="差旅费用" value="travel" />
            <el-option label="办公费用" value="office" />
            <el-option label="人员费用" value="personnel" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="需要审批" prop="needApproval">
          <el-switch v-model="form.needApproval" />
          <span class="form-tip">开启后该类型费用需要审批</span>
        </el-form-item>
        <el-form-item label="审批流程" prop="approvalFlow" v-if="form.needApproval">
          <el-select v-model="form.approvalFlow" placeholder="请选择审批流程">
            <el-option label="一级审批" value="level1" />
            <el-option label="二级审批" value="level2" />
            <el-option label="三级审批" value="level3" />
          </el-select>
        </el-form-item>
        <el-form-item label="限额" prop="limitAmount">
          <el-input-number v-model="form.limitAmount" :min="0" :step="100" />
          <span class="form-tip">单位：元，0表示无限制</span>
        </el-form-item>
        <el-form-item label="会计科目" prop="accountSubject">
          <el-input v-model="form.accountSubject" placeholder="请输入会计科目" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="form.remark" 
            type="textarea" 
            :rows="3"
            placeholder="请输入备注信息" 
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import ImportButton from '@/components/common/ImportButton.vue'
import ExportButton from '@/components/common/ExportButton.vue'

// 搜索表单
const searchForm = reactive({
  name: '',
  category: ''
})

// 选中的行
const selectedRows = ref([])

// 导出列配置
const exportColumns = [
  { prop: 'code', label: '类型代码' },
  { prop: 'name', label: '类型名称' },
  { prop: 'category', label: '费用类别' },
  { prop: 'needApproval', label: '需要审批' },
  { prop: 'limitAmount', label: '限额' },
  { prop: 'accountSubject', label: '会计科目' },
  { prop: 'status', label: '状态' },
  { prop: 'remark', label: '备注' }
]

// 表格数据
const tableData = ref([
  { id: 1, code: 'EXP001', name: '交通费', category: 'travel', needApproval: false, limitAmount: 0, accountSubject: '6601-差旅费', status: 1, remark: '包含打车、公交、地铁等' },
  { id: 2, code: 'EXP002', name: '住宿费', category: 'travel', needApproval: true, approvalFlow: 'level2', limitAmount: 500, accountSubject: '6601-差旅费', status: 1, remark: '出差住宿费用' },
  { id: 3, code: 'EXP003', name: '餐饮费', category: 'daily', needApproval: false, limitAmount: 100, accountSubject: '6602-业务招待费', status: 1, remark: '日常餐饮费用' },
  { id: 4, code: 'EXP004', name: '办公用品', category: 'office', needApproval: false, limitAmount: 0, accountSubject: '6603-办公费', status: 1, remark: '办公用品采购' },
  { id: 5, code: 'EXP005', name: '培训费', category: 'personnel', needApproval: true, approvalFlow: 'level3', limitAmount: 5000, accountSubject: '6604-职工教育经费', status: 1, remark: '员工培训费用' },
  { id: 6, code: 'EXP006', name: '通讯费', category: 'daily', needApproval: false, limitAmount: 200, accountSubject: '6605-通讯费', status: 1, remark: '电话费、网费等' },
  { id: 7, code: 'EXP007', name: '会议费', category: 'office', needApproval: true, approvalFlow: 'level2', limitAmount: 2000, accountSubject: '6606-会议费', status: 1, remark: '会议组织费用' },
  { id: 8, code: 'EXP008', name: '福利费', category: 'personnel', needApproval: true, approvalFlow: 'level2', limitAmount: 0, accountSubject: '6607-福利费', status: 1, remark: '员工福利支出' }
])

// 分页
const pagination = reactive({
  page: 1,
  size: 10,
  total: 8
})

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('新增费用类型')
const formRef = ref(null)

// 表单数据
const form = reactive({
  id: null,
  code: '',
  name: '',
  category: '',
  needApproval: false,
  approvalFlow: '',
  limitAmount: 0,
  accountSubject: '',
  sort: 0,
  status: 1,
  remark: ''
})

// 表单验证规则
const rules = {
  code: [{ required: true, message: '请输入类型代码', trigger: 'blur' }],
  name: [{ required: true, message: '请输入类型名称', trigger: 'blur' }],
  category: [{ required: true, message: '请选择费用类别', trigger: 'change' }]
}

// 获取类别标签
const getCategoryTag = (category) => {
  const tagMap = {
    daily: 'primary',
    travel: 'success',
    office: 'warning',
    personnel: 'danger',
    other: 'info'
  }
  return tagMap[category] || ''
}

// 获取类别名称
const getCategoryLabel = (category) => {
  const labelMap = {
    daily: '日常费用',
    travel: '差旅费用',
    office: '办公费用',
    personnel: '人员费用',
    other: '其他'
  }
  return labelMap[category] || category
}

// 搜索
const handleSearch = () => {
  console.log('搜索:', searchForm)
  ElMessage.success('查询成功')
}

// 重置
const handleReset = () => {
  searchForm.name = ''
  searchForm.category = ''
  handleSearch()
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 批量启用
const handleBatchEnable = () => {
  ElMessageBox.confirm(`确定要启用选中的 ${selectedRows.value.length} 个费用类型吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    selectedRows.value.forEach(row => {
      row.status = 1
    })
    ElMessage.success('批量启用成功')
    selectedRows.value = []
  })
}

// 批量停用
const handleBatchDisable = () => {
  ElMessageBox.confirm(`确定要停用选中的 ${selectedRows.value.length} 个费用类型吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    selectedRows.value.forEach(row => {
      row.status = 0
    })
    ElMessage.success('批量停用成功')
    selectedRows.value = []
  })
}

// 批量删除
const handleBatchDelete = () => {
  ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 个费用类型吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const ids = selectedRows.value.map(row => row.id)
    console.log('批量删除:', ids)
    ElMessage.success('批量删除成功')
    selectedRows.value = []
    handleSearch()
  })
}

// 导入成功回调
const handleImportSuccess = (result) => {
  console.log('导入成功:', result)
  ElMessage.success(`成功导入 ${result.validRows} 条数据`)
  handleSearch()
}

// 新增
const handleAdd = () => {
  dialogTitle.value = '新增费用类型'
  Object.assign(form, {
    id: null,
    code: '',
    name: '',
    category: '',
    needApproval: false,
    approvalFlow: '',
    limitAmount: 0,
    accountSubject: '',
    sort: 0,
    status: 1,
    remark: ''
  })
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑费用类型'
  Object.assign(form, { ...row })
  dialogVisible.value = true
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除费用类型 "${row.name}" 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    console.log('删除:', row.id)
    ElMessage.success('删除成功')
  })
}

// 切换状态
const handleToggleStatus = (row) => {
  const status = row.status === 1 ? 0 : 1
  const text = status === 1 ? '启用' : '停用'
  ElMessageBox.confirm(`确定要${text}费用类型 "${row.name}" 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    row.status = status
    ElMessage.success(`${text}成功`)
  })
}

// 提交表单
const handleSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      console.log('提交:', form)
      ElMessage.success(form.id ? '修改成功' : '新增成功')
      dialogVisible.value = false
      handleSearch()
    }
  })
}
</script>

<style scoped>
.page-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-form {
  margin-bottom: 20px;
}

.batch-actions {
  margin-bottom: 20px;
}

.batch-buttons {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}

.form-tip {
  margin-left: 10px;
  color: #999;
  font-size: 12px;
}
</style>

